class CreateGalleryTemplates < ActiveRecord::Migration
  # "_default.haml" must exist in app/views/galleries in order for this to work properly. Bad, I know. Should use Generators here.
  def self.up
    create_table :gallery_templates do |t|
      t.string  :name
      t.boolean :handles_add_to_cart
      t.boolean :handles_proofing
      t.boolean :handles_photos
      t.boolean :handles_videos
      t.timestamps
    end
    
    add_column :galleries, :gallery_template_id, :integer
    # add in defaults
    load_from_csv("gallery_templates", gallery_template_data)
    gallery_template = GalleryTemplate.find(:all).first
    Gallery.find(:all).each {|gallery| gallery.update_attributes!(:gallery_template => gallery_template, :users => gallery.users, :pages => gallery.pages)}
  end
  
  def self.load_from_csv(table_name, data)
    column_clause = nil
    is_header = false
    cnx = ActiveRecord::Base.connection
    ActiveRecord::Base.silence do
      reader = CSV::Reader.create(data)

      columns = reader.shift.map {|column_name| cnx.quote_column_name(column_name) }
      column_clause = columns.join(', ')

      reader.each do |row|
        next if row.first.nil? # skip blank lines
        raise "No table name defined" if !table_name
        raise "No header defined" if !column_clause
        values_clause = row.map {|v| cnx.quote(v).gsub('\\n', "\n").gsub('\\r', "\r") }.join(', ')
        sql = "INSERT INTO #{table_name} (#{column_clause}) VALUES (#{values_clause})"
        cnx.insert(sql)
      end
    end
  end
  
  def self.gallery_template_data
  <<'END_OF_DATA'
"id","name","handles_add_to_cart","handles_proofing","handles_photos","handles_videos","created_at","updated_at"
1,"default","1","1","1","1","",""
2,"fancy","1","1","1","0","",""
END_OF_DATA
  end

  def self.down
    drop_table      :gallery_templates
    remove_column   :galleries, :gallery_template_id
  end
end
